package resources 
{
	import app.textures.TextureInfo;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.Graphics;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import gui.LoaderIndicator;
	import utils.ErrorsCollector;
	/**
	 * ...
	 * @author Dmitriy Gaiduk
	 */
	public class ImageLoader 
	{
		private var _loader:Loader;
		private var _preloaderIndicator:LoaderIndicator;
		private var _imageHolder:Sprite;
		private var _imageName:String;
		
		public function ImageLoader(imgName:String) 
		{
			_imageName = imgName;
		}
		
		public function run():DisplayObject
		{
			if (_loader != null)
			{
				return null;
			}
			_loader = null;
			_loader = new Loader();
			_imageHolder = new Sprite();
			_imageHolder.addChild(_loader);
			configureListeners(_loader.contentLoaderInfo);
			
			// add preloader movie
			_preloaderIndicator = new LoaderIndicator();
			_preloaderIndicator.x = _preloaderIndicator.radius;
			_preloaderIndicator.y = _preloaderIndicator.radius;
			_imageHolder.addChild(_preloaderIndicator);
			
			try
			{
				_loader.load(new URLRequest(_imageName)); 
			}
			catch(er:Error)
			{
				handleError(er.message + "image: " + _imageName);
				return null;
			}
			return _imageHolder;
		}
		
		
		private function handleError(err:String):void
		{
			ErrorsCollector.collectError("Image Loader: " + err);
		}
		
		// добавляет обработчики событий
		private function configureListeners(dispatcher:IEventDispatcher):void 
		{
            dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
            dispatcher.addEventListener(Event.COMPLETE, handleLoadComplete);
			dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			
           /* dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
            dispatcher.addEventListener(Event.INIT, initHandler);
            dispatcher.addEventListener(Event.OPEN, openHandler);
            dispatcher.addEventListener(Event.UNLOAD, unLoadHandler);*/
        }
		
			
		// удаляет обработчики событий
		private function removeListeners(dispatcher:IEventDispatcher):void
		{
			dispatcher.removeEventListener(Event.COMPLETE, handleLoadComplete);
			dispatcher.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			dispatcher.removeEventListener(ProgressEvent.PROGRESS, progressHandler);
		}
		
		private function handleLoadComplete(e:Event):void 
		{
			removeListeners(_loader.contentLoaderInfo);
			if (_preloaderIndicator != null && _preloaderIndicator.parent != null)
			{
				_preloaderIndicator.parent.removeChild(_preloaderIndicator);
			}
			destroy();
		}
		
		private function httpStatusHandler(event:HTTPStatusEvent):void 
		{
            //handleError("httpStatusHandler: " + event);
        }

        private function initHandler(event:Event):void 
		{
            //handleError("initHandler: " + event);
        }

        private function ioErrorHandler(event:IOErrorEvent):void 
		{
			//ошибка загрузки
            handleError("Load image error: " + event.text + " file: " + _imageName);
        }

        private function openHandler(event:Event):void 
		{
            //trace("openHandler: " + event);
        }

        private function progressHandler(event:ProgressEvent):void 
		{
			if (_preloaderIndicator != null)
			{
				if (event.bytesTotal != 0)
				{
					_preloaderIndicator.setPercent(event.bytesLoaded / event.bytesTotal * 100);
				}
			}
            //trace("progressHandler: bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal);
        }

        private function unLoadHandler(event:Event):void 
		{
            //trace("unLoadHandler: " + event);
        }
		
		public function destroy():void
		{
			_preloaderIndicator = null;
			_loader = null;
		}
		
	}

}